package com.wzt.lianfirecontrol.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.AppVersionModel;
import com.wzt.lianfirecontrol.bean.recode.user.CompanyModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.SimpleCache;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class LoginActivity extends BaseActivity {

    private EditText et_username;
    private ImageView iv_user_clear;
    private EditText et_password;
    private ImageView iv_password_clear;
    private ImageView iv_login_btn;

    private static final int LOGIN_WHAT = 0;
    private static final int GET_COMPANY_WHAT = 1;// 获取公司树
    private static final int APP_UPDATE_WHAT = 2;

    private Dialog updateDialog;

    private Dialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_login);
        setImmerseLayout();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle && bundle.containsKey("code_msg")){
            String code_msg = bundle.getString("code_msg");
            ToastUtils.showToast(this, code_msg);
        }
        UserInfoModel.clearUserLoginMessage(this);
        initView();
        et_username.setText(UserInfoModel.getUserAccount(this));
    }

    private void initView() {
        et_username = findViewById(R.id.et_username);
        iv_user_clear = findViewById(R.id.iv_user_clear);
        iv_user_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_username.setText("");
            }
        });
        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String userAccount = et_username.getText().toString();
                if (StringUtils.isEmpty(userAccount)){
                    iv_user_clear.setVisibility(View.GONE);
                }else {
                    iv_user_clear.setVisibility(View.VISIBLE);
                    if (!StringUtils.isEmpty(userAccount) && userAccount.equals(UserInfoModel.getUserAccount(LoginActivity.this))){
                        et_password.setText(UserInfoModel.getUserPassword(LoginActivity.this));
                    }
                }
            }
        });

        et_password = findViewById(R.id.et_password);
        iv_password_clear = findViewById(R.id.iv_password_clear);
        iv_password_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_password.setText("");
            }
        });
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (StringUtils.isEmpty(et_password.getText().toString())){
                    iv_password_clear.setVisibility(View.GONE);
                }else {
                    iv_password_clear.setVisibility(View.VISIBLE);
                }
            }
        });

        iv_login_btn = findViewById(R.id.iv_login_btn);
        Glide.with(this).asGif().load(R.drawable.icon_login_btn).into(iv_login_btn);
        iv_login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUtils.isEmpty(et_username.getText().toString())){
                    ToastUtils.showToast(LoginActivity.this, "用户名不能为空");
                    return;
                }
                if (StringUtils.isEmpty(et_password.getText().toString())){
                    ToastUtils.showToast(LoginActivity.this, "密码不能为空");
                    return;
                }
                if (!Utils.hasNetwork(LoginActivity.this)){
                    ToastUtils.showToast(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.no_net));
                    return;
                }
                // 发送登录请求
                initLoginHttpHelper(et_username.getText().toString(), et_password.getText().toString());
            }
        });
        findViewById(R.id.tv_forget_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginActivity.this.skipToForgetPs("0");
            }
        });

    }

    private void initLoginHttpHelper(String userName, String userPassword) {
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("username", userName);
            hashMap.put("password", userPassword);
            hashMap.put("terminal", "App");
            HashMap<String, String> url_params = new HashMap<>();
            url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
            LoginHttpHelper loginHttpHelper = new LoginHttpHelper(this,
            Url.LOGIN_URL, LOGIN_WHAT, handler, true, url_params);
            loginHttpHelper.setParseJsonData(new LoginParseJsonData());
            loginHttpHelper.getHttpRequest(true);
        }catch (Exception e){}
    }

    /**
     * 获取公司树
     */
    private void initGetCompanyHttpHelper(){
        HashMap<String, String> url_params = new HashMap<>();
        LoginHttpHelper getCompanyHttpHelper = new LoginHttpHelper(this, Url.QUERY_COMPANY_TREE, GET_COMPANY_WHAT, handler, true, url_params);
        getCompanyHttpHelper.setParseJsonData(new LoginParseJsonData());
        getCompanyHttpHelper.getHttpRequest();
    }

    private void initUpdateHttpHelper(){
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("version", "V" + Utils.getVersionName(this));
            hashMap.put("terminal", "App");
            HashMap<String, String> url_params = new HashMap<>();
            url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
            LoginHttpHelper infoListListHttpHelper = new LoginHttpHelper(this,
                    Url.APP_UPDATE_URL, APP_UPDATE_WHAT, handler, true, url_params);
            infoListListHttpHelper.setParseJsonData(new LoginParseJsonData());
            infoListListHttpHelper.getHttpRequest(true);
        }catch (Exception e){}
    }


    class LoginHttpHelper extends HttpHelper{

        public LoginHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class LoginParseJsonData extends ParseJsonData {

        public LoginParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {

                switch (what){
                    case LOGIN_WHAT:
                        JSONObject jsonObject = new JSONObject(dataStr);
                        // 返回token和user
                        String token = jsonObject.getString("token");
                        String user = jsonObject.getString("user");
                        PreferencesUtils.putString(LoginActivity.this, ConstData.USERINFO, user);
                        UserInfoModel userInfoModel = JSONUtil.jsonObjectToBean(new JSONObject(user), UserInfoModel.class);
                        UserInfoModel.setCompandId(LoginActivity.this, userInfoModel.getCompanyId());
                        UserInfoModel.setRepairCompanyId(LoginActivity.this,userInfoModel.getRepairCompanyId());
                        UserInfoModel.setCompandName(LoginActivity.this, userInfoModel.getCompanyName());
                        if (!StringUtils.isEmpty(token)){
                            bundle.putString("token", token);
                            bundle.putBoolean(REQUEST_OK, true);
                        }else {
                            bundle.putBoolean(REQUEST_OK, false);
                            bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                        }
                        break;
                    case GET_COMPANY_WHAT:
                        LinkedList<CompanyModel> companyModels = (LinkedList<CompanyModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), CompanyModel.class);
                        bundle.putSerializable("companyList", companyModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case APP_UPDATE_WHAT:
                        JSONObject jsonObject1 = new JSONObject(dataStr);
                        AppVersionModel appVersionModel = JSONUtil.jsonObjectToBean(new JSONObject(jsonObject1.getString("appVersion")), AppVersionModel.class);
                        bundle.putSerializable("data", appVersionModel);
                        bundle.putString("upgrade", jsonObject1.getString("upgrade"));
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                bundle.putBoolean(REQUEST_OK, false);
                bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(this, bundle.getString(ParseJsonData.ERROR_MSG));
            return;
        }
        switch (msg.what){
            case LOGIN_WHAT:
                String token = bundle.getString("token");
                if (!StringUtils.isEmpty(token)){
                    UserInfoModel.setUserAccount(LoginActivity.this, et_username.getText().toString());
                    UserInfoModel.setUserPassword(LoginActivity.this, et_password.getText().toString());
                    UserInfoModel.setUserToken(this, token);
                    UserInfoModel.setUserLoginMessage(this);
                    if (StringUtils.isEmpty(UserInfoModel.getCompandId(this))){
                        initGetCompanyHttpHelper();
                    }else {
                        openActivity(MainActivity.class);
                        finish();
                    }
                }

                break;
            case GET_COMPANY_WHAT:
                List<CompanyModel> companyModels = (List<CompanyModel>) bundle.getSerializable("companyList");
                if (null != companyModels && companyModels.size() > 0) {
                    UserInfoModel.setCompandId(this, companyModels.get(0).getId());
                    UserInfoModel.setCompandName(LoginActivity.this, companyModels.get(0).getName());
                    openActivity(MainActivity.class);
                    finish();
                }else {
                    ToastUtils.showToast(this, "权限不足");
                }
                break;
            case APP_UPDATE_WHAT:

                String upgrade = bundle.getString("upgrade");
                if ("true".equals(upgrade)) {
                    AppVersionModel appVersionModel = (AppVersionModel) bundle.getSerializable("data");
                    updateDialog = DialogUtils.createAppUpdateDialog(this, appVersionModel);
                    if ("1".equals(appVersionModel.getForceUpdate()) || !SimpleCache.isContainValueForOneDay(this, ConstData.UPDATE_DIALOG_SHOW, "1")) {
                        DialogUtils.showDialog(updateDialog);
                    }
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != et_username) {
            String userAccount = et_username.getText().toString();
            if (!StringUtils.isEmpty(userAccount) && userAccount.equals(UserInfoModel.getUserAccount(LoginActivity.this))) {
                et_password.setText(UserInfoModel.getUserPassword(LoginActivity.this));
            }
        }
        if (null == updateDialog || !updateDialog.isShowing()) {
            initUpdateHttpHelper();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(updateDialog);
    }
}
